package com.example.myapplication2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class UserMessageAdapter extends RecyclerView.Adapter<UserMessageAdapter.UserMessageViewHolder> {

    private final List<UserMessage> mUserWordMessageList;

    UserMessageAdapter(List<UserMessage> userWordMessageList) {
        mUserWordMessageList = userWordMessageList;
    }

    @NonNull
    @Override
    public UserMessageAdapter.UserMessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {//用来创建ViewHolder
        if(viewType==UserMessage.TYPE_RECEIVE){//如果是收到的消息，那么就是receive格式，显示在屏幕的左侧
            View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.left_layout,parent,false);
            return new UserMessageViewHolder(view);
        }
        else{//否则就是属于用户发送的信息，显示在屏幕右侧
            View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.right_layout,parent,false);
            return new UserMessageViewHolder(view);
        }


    }

    @Override
    public void onBindViewHolder(@NonNull UserMessageAdapter.UserMessageViewHolder holder, int position) {//调用此方法将 ViewHolder 与数据相关联
        UserMessage msg=mUserWordMessageList.get(position);//根据不同消息选择不同的布局
        if(msg.getType()==UserMessage.TYPE_RECEIVE){
            holder.tvLeft.setText(msg.getContent());
        }
        else{
            holder.tvRight.setText(msg.getContent());
        }
    }

    public int getItemViewType(int position){
        UserMessage msg =mUserWordMessageList.get(position);
        return msg.getType();
    }


    @Override
    public int getItemCount() {//RecyclerView 调用此方法来获取数据集的大小
        return mUserWordMessageList.size();
    }

    class UserMessageViewHolder extends RecyclerView.ViewHolder {
        TextView tvLeft, tvRight;

        UserMessageViewHolder(@NonNull View itemView) {
            super(itemView);

            tvLeft = itemView.findViewById(R.id.message_left);
            tvRight = itemView.findViewById(R.id.message_right);
        }
    }
}
